<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-01 10:07:47
 * @LastEditTime: 2024-02-04 13:09:19
-->
<script lang="ts" setup name="DepModal">
import { paramType } from 'iking-utils'
import type { PropType, Ref } from 'vue'
import { useFormRules } from '@g/hooks/use-rules'
import { depApi } from '@/MainApp/apis/dep'

const props = defineProps({
  selectDepNode: {
    type: Object as PropType<typeof form.value | null | undefined>,
    default: () => null
  },
  isEditing: {
    type: Boolean,
    default: false
  },
  orgId: {
    type: String,
    default: ''
  }
})
const emits = defineEmits<{
  (e: 'handConfirm', id: string): void
}>()
const { dialog, t } = useConfig()
const { lenPhone, lenShort } = useLength()
const { msgError } = useMessage()
const visible: Ref<any> | undefined = inject('visible')
const depChange: Ref<Boolean> | undefined = inject('depChange')

const placeholder = {
  name: '请输入部门名称',
  phone: '请输入联系电话',
  typePhone: '联系电话格式不正确',
  userCount: '请输入部门用户数量'
}
const formKey: { [key: string]: any; } = {
  // 部门名称
  name: '',
  // 主管
  managerId: null,
  // 所属组织编号
  orgId: '',
  // 父级部门编号
  parentId: '',
  // 联系电话
  phone: ''
}
const depState = reactive({
  title: '新增部门',
  loading: false
})
const form = ref({ ...formKey })
const depRef = ref()
const deptParams = ref<any>(null)
const excludeId = ref<string>('')
const depRules = useFormRules([{
  key: 'name',
  required: true,
  msg: placeholder.name,
  trigger: 'blur'
}, {
  key: 'phone',
  type: 'telephone',
  required: false,
  msg: placeholder.phone,
  trigger: 'blur',
  typeMsg: placeholder.typePhone
}])
const handleClose = () => {
  visible!.value = false
  depState.loading = false
  depRef.value?.resetFields()
  form.value = { ...formKey }
  depState.title = '新增部门'
  depChange!.value = false
}
watch(
  () => visible!.value,
  () => {
    form.value.parentId = props.selectDepNode?.id || ''
    form.value.orgId = props.orgId || '' // 组织id
    if (visible!.value && props.isEditing) {
      form.value = { ...props.selectDepNode }
      depState.title = '修改部门'
      // deptParams.value = {
      //   deptId: props.selectDepNode?.id,
      //   excludeCurrentAndSub: true
      // }
      deptParams.value = props.selectDepNode?.id
      excludeId.value = props.selectDepNode?.id
    }
    else {
      deptParams.value = null
      excludeId.value = ''
    }
  }
)

// 新增、修改
const handConfirm = () => {
  depRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      depState.loading = true
      const _param = {
        ...form.value,
        managerId: form.value.managerId
          ? paramType.isArray(form.value.managerId)
            ? form.value.managerId.join(',')
            : form.value.managerId
          : ''
      }
      const { msg, success } = props.isEditing
        ? await depApi.updateDep(_param)
        : await depApi.addDep(_param)
      if (success) {
        emits('handConfirm', form.value.orgId)
        handleClose()
        depChange!.value = true
      }
      else {
        msgError(msg)
      }
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="depState.title"
    draggable
    :width="dialog.sl"
    destroy-on-close
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <el-form
      ref="depRef"
      :model="form"
      :rules="depRules"
      label-width="90px"
      label-position="top"
    >
      <el-form-item label="父级部门" prop="parentId">
        <IkSelectDep
          v-model="form.parentId"
          placeholder="请选择父级部门"
          check-strictly
          clearable
          :dept-params="deptParams"
          :exclude-id="excludeId"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model.trim="form.name"
          clearable
          :placeholder="placeholder.name"
          :maxlength="lenShort"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model.trim="form.phone"
          clearable
          :placeholder="placeholder.phone"
          :maxlength="lenPhone"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="部门主管" prop="managerId">
        <IkPersonSelect
          v-model="form.managerId"
          clearable
          title="部门主管"
          :multiple="false"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        bg
        text
        @click="handleClose"
      >
        {{ t('action.cancel') }}
      </el-button>
      <el-button
        type="primary"
        :loading="depState.loading"
        @click="handConfirm"
      >
        {{ t('action.sure') }}
      </el-button>
    </template>
  </el-dialog>
</template>
